package com.hex.ds.hdtp.core.app.common.util;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelExtendUtil {

    public static void datatoResponse(HttpServletRequest request, HttpServletResponse response, Workbook workbook, String fileName) throws IOException {
        OutputStream bufferedOutPut = null;
        try {
            // 2. 告诉浏览器下载的方式以及一些设置
            // 解决文件名乱码问题，获取浏览器类型，转换对应文件名编码格式，IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码
            String agent = request.getHeader("user-agent");
            if (agent.contains("FireFox")) {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            // 设置下载文件的mineType，告诉浏览器下载文件类型
            String mineType = request.getServletContext().getMimeType(fileName);
            response.setContentType(mineType);
            // 设置一个响应头，无论是否被浏览器解析，都下载
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            // 将要下载的文件内容通过输出流写到浏览器
            bufferedOutPut = response.getOutputStream();
            bufferedOutPut.flush();
            workbook.write(bufferedOutPut);
            bufferedOutPut.close();
        } catch (IOException e) {
            log.error("导出失败", e.getStackTrace());
            throw e;
        } finally {
            if (bufferedOutPut != null) {
                bufferedOutPut.close();
            }
        }
    }


}
